package com.hhsj.androidserver;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class WebApp {

    private static class IN {
        static final WebApp INSTANCE = new WebApp();
    }

    private final ServletContext context;


    public static WebApp getInstance() {
        return IN.INSTANCE;
    }

    public void init(ServletList servletList) {
        List<Class<? extends HttpServlet>> servletList1 = servletList.getServletList();
        Map<String, String> servlet = context.getServlet();
        for (Class clazz : servletList1) {
            WebServlet ws = (WebServlet) clazz.getAnnotation(WebServlet.class);
            if (ws != null) {
                servlet.put(ws.value(), clazz.getName());
            }
        }
    }
//
//    private void setPackageName(String packageName) {
//        Map<String, String> servlet = context.getServlet();
//        Iterator<Class<?>> clas = PackageScanUtils.getClasses(packageName, true).iterator();
//        while (clas.hasNext()) {
//            Class<?> cla = clas.next();
//            WebServlet ws = cla.getAnnotation(WebServlet.class);
//            if (ws != null) {
//                servlet.put(ws.value(), cla.getName());
//            }
//        }
//    }


    private WebApp() {
        context = new ServletContext();
    }

    /**
     * 获取url地址
     *
     * @param url
     * @return
     */
    public HttpServlet getServlet(String url) {
        Map<String, String> temp = context.getServlet();
        if (temp.containsKey(url)) {
            try {
                return (HttpServlet) Class.forName(temp.get(url)).newInstance();
            } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static class ServletContext {

        private final Map<String, String> servlet;

        ServletContext() {
            servlet = new HashMap<>();
        }

        Map<String, String> getServlet() {
            return servlet;
        }

    }
}